<template>
  <!--
  难点:
  1. 获取过来的数据的储存
  2. 两个添加按钮共有一个弹出层
  3. 添加时,数据复杂
  4. 编辑操作提交之前数据的保存

  提示:
  1. 依赖计算属性
  2. 查看接口文档提前获取并保存参数
  3. 重点关注数据的流向以及数据的保存方式及位置
 -->
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片面板 -->
    <el-card>
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 商品分类下拉列表 -->
      <p>
        选择商品分类:
        <el-cascader
          v-model="selectedKeys"
          :options="cateList"
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id',
          }"
          clearable
          @change="handleCascaderChange"
        ></el-cascader>
      </p>
      <!-- Tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handelTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handelClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 新增按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引行 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                ></el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParamById(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handelClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 新增按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                ></el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParamById(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加弹出层 -->
    <el-dialog
      :title="'新增' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="130px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹出层 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="130px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // -------------所有的商品分类列表-------------
      cateList: [],
      // -------------选中的分类id数组-------------
      selectedKeys: [1, 4, 23], // 测试代码(后期删除数据)
      // -------------Tab栏的默认选中项-------------
      activeName: 'only',
      // -------------动态参数的数据-------------
      manyTableData: [],
      // -------------静态属性的数据-------------
      onlyTableData: [],
      // -------------添加弹出层依赖-------------
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // -------------修改弹出层依赖-------------
      editDialogVisible: false,
      editForm: {
        attr_id: '',
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
    this.getParamsData() // 测试代码(后期删除)
  },
  methods: {
    // -------------获取所有的商品分类列表-------------
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    // -------------监听级联选择器的改变事件(实现只允许选中三级分类)-------------
    handleCascaderChange () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getParamsData()
    },
    // -------------发起请求获取参数和属性(公共参数)-------------
    async getParamsData () {
      const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: this.activeName } })
      // 在保存数据之前,将字符串转换为数组
      res.data.forEach(item => {
        // 分割之前,做非空验证
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 设置自定义属性(为每一条数据添加自己的属性(避免相互干扰))
        item.inputVisible = false
        item.inputValue = ''
      })
      // 将获取到的数据存放到data中
      // 1. 简化写法
      this[this.activeName + 'TableData'] = res.data

      // 2. 一般写法
      // if (this.activeName === 'many') {
      //   this.manyTableData = res.data
      // } else {
      //   this.onlyTableData = res.data
      // }
    },
    // -------------点击页签后也要发送请求-------------
    handelTabClick () {
      this.getParamsData()
    },
    // -------------添加弹出层依赖-------------
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    addParams () {
      this.$refs.addFormRef.validate(async (isValid) => {
        if (isValid) {
          const { data: res } = await this.$http.post('categories/' + this.cateId + '/attributes', {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status === 201) {
            this.$message({
              message: '添加成功',
              type: 'success',
              showClose: true,
              duration: 3000
            })
            this.getParamsData()
            this.addDialogVisible = false
          } else {
            this.$message({
              message: '添加失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          }
        }
      })
    },
    // -------------修改弹出层依赖-------------
    showEditDialog (row) {
      this.editForm.attr_id = row.attr_id
      this.editForm.attr_name = row.attr_name
      this.editDialogVisible = true
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    editUser () {
      this.$refs.editFormRef.validate(async (isValid) => {
        if (isValid) {
          const { data: res } = await this.$http.put('categories/' + this.cateId + '/attributes/' + this.editForm.attr_id, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status === 200) {
            this.$message({
              message: '编辑成功',
              type: 'success',
              showClose: true,
              duration: 3000
            })
            this.getParamsData()
            this.editDialogVisible = false
          } else {
            this.$message({
              message: '编辑失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          }
        }
      })
    },
    // -------------删除功能实现-------------
    removeParamById (row) {
      // 通过elmecon
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        // 确定
        await this.$http.delete('categories/' + this.cateId + '/attributes/' + row.attr_id)
        this.getParamsData()
        this.$message({
          message: '删除成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      }).catch(() => {
        // 取消
      })
    },
    // -------------新增tag功能实现-------------
    showInput (row) {
      row.inputVisible = true
      // 当DOM元素发生重新渲染后会执行$nextTick() 方法中的回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async saveAttrValues (row) {
      await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      this.$message.success('修改成功!')
    },

    handleInputConfirm (row) {
      if (row.inputValue) {
        row.attr_vals.push(row.inputValue)
        this.saveAttrValues(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    handelClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrValues(row)
    }

    // -------------methods end-------------
  },
  // -------------计算属性立大功-------------
  computed: {
    // -------------控制添加按钮的状态-------------
    isBtnDisabled () {
      return this.selectedKeys.length !== 3
    },
    // -------------获取查询参数的id-------------
    cateId () {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    // -------------添加参数/属性的标题文字-------------
    titleText () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
